/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.byox.drawview.utils;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;

/**
 * 类似 BitmapFactory.decodeResource 获取 Bitmap
 * ImageSource.DecodingOptions可以自己按需求添加其他属性
 *
 * @since 2021-03-18
 */
public class PixelMapFactoryUtil {
    private static final String FORMAT = "image/png";

    private static final String TAG = PixelMapFactoryUtil.class.getSimpleName();
    private static HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, TAG);

    private PixelMapFactoryUtil() {
    }

    /**
     * 获取解码属性
     *
     * @return 解码属性
     */
    public static ImageSource.DecodingOptions getDecodingOptions() {
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.desiredSize = new Size(0, 0);
        decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;

        return decodingOptions;
    }

    /**
     * 根据存储路径获取图片
     *
     * @param path
     * @param decodingOptions
     * @return 图片
     */
    public static PixelMap getPixelMapFromPath(String path, ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap = null;
        try {
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(path, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IllegalArgumentException e) {
            HiLog.error(logLabel, e.getMessage());
        }

        return pixelmap;
    }

    /**
     * 根据资源文件获取图片
     *
     * @param context
     * @param resId
     * @param decodingOptions
     * @return 图片
     */
    public static PixelMap getPixelMapFromResource(Context context, int resId,
                                                   ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap = null;
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(drawableInputStream, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IOException | NotExistException e) {
            HiLog.error(logLabel, e.getMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (IOException e) {
                HiLog.error(logLabel, e.getMessage());
            }
        }
        return pixelmap;
    }

    /**
     * 从指定字节数组解码图片
     *
     * @param data
     * @param offset
     * @param length
     * @param decodingOptions
     * @return 图片
     */
    public static PixelMap getPixelMapFromArray(byte[] data, int offset, int length,
                                                ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap = null;
        try {
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(data, offset, length, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IllegalArgumentException e) {
            HiLog.error(logLabel, e.getMessage());
        }

        return pixelmap;
    }

    /**
     * 通过流数据解码图片
     *
     * @param inputStream
     * @param decodingOptions
     * @return 图片
     */
    public static PixelMap getPixelMapFromInputStream(InputStream inputStream,
                                                      ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap = null;
        try {
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(inputStream, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IllegalArgumentException e) {
            HiLog.error(logLabel, e.getMessage());
        }
        return pixelmap;
    }

    /**
     * 通过文件描述解码图片
     *
     * @param fileDescriptor
     * @param decodingOptions
     * @return 图片
     */
    public static PixelMap getPixelMapFromFileDescriptor(FileDescriptor fileDescriptor,
                                                         ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap = null;
        try {
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(fileDescriptor, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IllegalArgumentException e) {
            HiLog.error(logLabel, e.getMessage());
        }
        return pixelmap;
    }

    /**
     * createBitmap 方法
     *
     * @param pixelMap 源pixmap对象
     * @return 返回保存生成图片所需的pixmap
     */
    public static PixelMap createBitmap(PixelMap pixelMap) {
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.size = new Size(pixelMap.getImageInfo().size.width, pixelMap.getImageInfo().size.height);
        options.pixelFormat = PixelFormat.ARGB_8888;
        PixelMap bitmap = PixelMap.create(options);
        Texture texture = new Texture(bitmap);
        Canvas canvas = new Canvas(texture);
        Paint paint = new Paint();
        canvas.drawRect(0, 0, pixelMap.getImageInfo().size.width, pixelMap.getImageInfo().size.height, paint);
        canvas.drawPixelMapHolder(new PixelMapHolder(pixelMap), 0, 0, paint);
        return bitmap;
    }

    /**
     * getSavePixelMap 方法
     *
     * @param src 源pixmap
     * @param watermark 叠加pixmap
     * @param paddingLeft 左边距
     * @param paddingTop 上边距
     * @return 合成的pixmap
     */
    public static PixelMap getSavePixelMap(PixelMap src, PixelMap watermark, int paddingLeft, int paddingTop) {
        int width = src.getImageInfo().size.width;
        int height = src.getImageInfo().size.height;
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.size = new Size(width, height);
        initializationOptions.editable = true;
        PixelMap pixelMap = PixelMap.create(initializationOptions);
        Canvas canvas = new Canvas(new Texture(pixelMap));
        Paint paint = new Paint();
        canvas.drawPixelMapHolder(new PixelMapHolder(src), 0, 0,paint);
        canvas.drawPixelMapHolder(new PixelMapHolder(watermark), paddingLeft, paddingTop, paint);

        return pixelMap;
    }
}
